using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Core.Exceptions;

namespace Core.Model
{
    public class TicTacToe
    {
        private readonly Player _player1;
        private readonly Player _player2;
        private Player _winner;
        private Player[,] _places = new Player[3, 3];
        private Player _turn = null;
        private int _moveCount = 0;
        //private Player[] _gameStore = new Player[9];
        public enum _GameState
        {
            GameInProgess, PlayerWins, GameDrawn
        };
        private _GameState _currentStateOfTheGame;

        public TicTacToe(Player player1, Player player2)
        {
            _player1 = player1;
            _player2 = player2;
            _currentStateOfTheGame = _GameState.GameInProgess;
        }

        public Player Player1
        {
            get { return _player1; }
        }

        public Player Player2
        {
            get { return _player2; }
        }

        public Player Winner
        {
            get { return _winner; }
        }

        public _GameState GameStatus
        {
            get{ return _currentStateOfTheGame; }
        }

        public Player Turn
        {
            get { return _turn; }
            set { _turn = value; }
        }
        
        public void PlaceAPiece(Player player, int x, int y)
        {
            if (_turn != null)
                if (_turn.Equals(player)) throw new ConsecutiveMoveException("Consecutive move not allowed");
            _turn = player;

            if (_places.GetValue(x, y) != null) throw new SquareTakenException("Square already taken");
            _places.SetValue(player, x, y);
            //_gameStore[x * 2 + y] = player;
            _moveCount++;

            CheckIfThePlayerHasWon(player, x, y);
        }

        private void CheckIfThePlayerHasWon(Player player, int x, int y)
        {
            int n = 3; //size of the board
            int col, row, diag, rdiag;
            col = row = diag = rdiag = 0;

            for (int i = 0; i < n; i++) //_places.Length
            {

                if (_places[x, i] == player)
                    col++;

                if (_places[i, y] == player)
                    row++;

                if (_places[i, i] == player)
                    diag++;

                if (_places[i, n - i - 1] == player)
                    rdiag++;

                if (row == n || col == n || diag == n || rdiag == n)
                {
                    _winner = player;
                    _currentStateOfTheGame = _GameState.PlayerWins;
                }

                if (_winner == null && _moveCount == Math.Pow(n,2))
                {
                    _currentStateOfTheGame = _GameState.GameDrawn;
                }
            }

        }
    }
}
